package com.czy.owner.ui.workorder;

import android.content.Intent;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.czy.owner.R;
import com.czy.owner.adapter.OrderMultiStyleAdapter;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.MyOrderModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.ui.BaseFragment;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.easyrecycleview.EasyRecyclerView;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by wangyang on 2016/7/8 0008.
 * 待服务
 */
public class ToBeServedFragment extends BaseFragment implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.recyclerView)
    EasyRecyclerView recyclerView;
    private OrderMultiStyleAdapter adapter;
    private int page = 1;
    private Handler handler = new Handler();
    private String session = "";
    private List<MyOrderModel> dataList = new ArrayList<>();

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_base_subcribeorder;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        init();
    }

    @Override
    protected void updateViews() {
        onRefresh();
    }

    private void init() {
        session = UserHelper.getInstance().getSessionInfoModel(getActivity()).getSession();
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapterWithProgress(adapter = new OrderMultiStyleAdapter(getActivity()));
        recyclerView.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.VERTICAL, R.drawable.shape_order_fragment_recyclerview_divider_decoration));
        recyclerView.setEmptyView(R.layout.order_empty_view);
        recyclerView.setErrorView(R.layout.view_error_refresh);
        adapter.setNoMore(R.layout.view_nomore);
        adapter.setMore(R.layout.view_more, this);
//        adapter.setError(R.layout.view_error_click).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                adapter.resumeMore();
//            }
//        });
        recyclerView.setRefreshListener(this);


        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener<MyOrderModel>() {
            @Override
            public void onItemClick(View view, int position, MyOrderModel model) {
                Intent ti = new Intent(getActivity(), OrderDetailActivity2.class);
                ti.putExtra("orderNumber", model.getOrderNumber());
                startActivity(ti);

            }
        });

    }

    @Override
    public void onLoadMore() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新
                if (!PhoneUtils.isNetworkConnected(getActivity())) {
                    adapter.pauseMore();
                    recyclerView.showError();
                    return;
                }
                page++;
                getDataList(false);

            }
        }, 1000);
    }

    @Override
    public void onRefresh() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新
                if (!PhoneUtils.isNetworkConnected(getActivity())) {
                    adapter.pauseMore();
                    recyclerView.showError();
                    return;
                }
                page = 1;
                getDataList(true);
            }
        }, 1000);
    }

    public void getDataList(final boolean isfirst) {
        String url = Constants.APP_API_BASE + Constants.OWN_ORDER_MYORDERS;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", session);
        params.addBodyParameter("storeId", SharedPreferencesUtils.getParam(getActivity(), UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        params.addBodyParameter("status", "waitService");
        params.addBodyParameter("page", page + "");
        params.addBodyParameter("size", "10");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                String data = PhoneUtils.checkResponseFlag(getActivity(), result);
                String list = JsonUtil.getJsonValuesString(data, "list");
                try {
                    if (data != null) {
                        dataList.clear();
                        Gson gson = new GsonBuilder().create();
                        dataList = gson.fromJson(list, new TypeToken<List<MyOrderModel>>() {
                        }.getType());
                        if (isfirst) {
                            adapter.clear();
                        }
                        if (dataList.size() < 9) {
                            adapter.stopMore();
                        }
                        adapter.addAll(dataList);

                    } else {
                        adapter.addAll(dataList);

                    }
                } catch (Exception e) {

                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });


    }

    @Override
    public void reloadData() {
        //刷新
        if (!PhoneUtils.isNetworkConnected(getActivity())) {
            if (adapter != null)
                adapter.pauseMore();
            return;
        }
        page = 1;
        getDataList(true);
    }
}